#include "client.h"

static shm_fifo_t *g_shm_fifo = NULL;
int g_msgid = 0;

void client_init()
{
    // 环形队列初始化
    g_shm_fifo = shm_fifo_init(10, sizeof(packet_t));

    // 消息队列初始化
    g_msgid = msg_create();
}

void *do_client_subscribe(void *arg)
{
    char buffer[32];

    for (;;)
    {
        memset(buffer, 0, sizeof(buffer));
        msg_rcv(g_msgid, getpid(), buffer, sizeof(buffer));
        printf("message:<%s>\n", buffer);
    }

    pthread_exit(NULL);
}

void subscribe(char *topic)
{
    packet_t packet;
    pthread_t tid;

    tid = pthread_create(&tid, NULL, do_client_subscribe, NULL);
    if (tid != 0)
    {
        perror("pthread_create()");
        return;
    }

    pthread_detach(tid);

    strcpy(packet.topic, topic);
    packet.pid = getpid();
    packet.mode = SUBSCRIBE;

    shm_fifo_write(g_shm_fifo, &packet);
}

// 发布消息
void publish(char *topic, char *content)
{
    packet_t packet;

    strcpy(packet.topic, topic);
    strcpy(packet.content, content);
    packet.pid = getpid();
    packet.mode = PUBLISH;

    shm_fifo_write(g_shm_fifo, &packet);
}